package com.gaohc.system.sysuser;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.gaohc.common.annotation.Log;
import com.gaohc.common.config.SystemConfig;
import com.gaohc.common.constant.UserConstants;
import com.gaohc.common.core.controller.BaseController;
import com.gaohc.common.core.domain.AjaxJson;
import com.gaohc.common.core.domain.entity.SysUser;
import com.gaohc.common.enums.BusinessType;
import com.gaohc.common.exception.BusinessException;
import com.gaohc.common.utils.DateUtils;
import com.gaohc.common.utils.StringUtils;
import com.gaohc.common.utils.file.FileUploadUtils;
import com.gaohc.system.vo.UpdatePwdVO;
import com.gaohc.system.sysuser.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 * 
 * @author ruoyi
 */
@SaCheckLogin
@Slf4j
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController
{
    @Resource
    private ISysUserService userService;

    /**
     * 个人信息
     */
    @GetMapping()
    public AjaxJson profile() {
        Map<String, Object> mmap = new HashMap<>();
        SysUser user = userService.getUserInfoById(getUserId());
        SysUser sysUser = new SysUser();
        sysUser.setUserId(user.getUserId());
        sysUser.setUserName(user.getUserName());
        sysUser.setNickName(user.getNickName());
        sysUser.setPhonenumber(user.getPhonenumber());
        sysUser.setEmail(user.getEmail());
        sysUser.setCreateTime(user.getCreateTime());
        sysUser.setSex(user.getSex());
        mmap.put("user", sysUser);
        mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId()));
        return AjaxJson.getSuccessData(mmap);
    }

    /**
     * 修改个人信息
     */
    @Log(title = "修改个人信息", businessType = BusinessType.UPDATE)
    @PutMapping()
    public AjaxJson updateUser(@RequestBody SysUser user) {
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            throw new BusinessException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            throw new BusinessException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(getUserId());
        sysUser.setNickName(user.getNickName());
        sysUser.setPhonenumber(user.getPhonenumber());
        sysUser.setEmail(user.getEmail());
        sysUser.setSex(user.getSex());
        userService.updateById(sysUser);
        userService.clearRedisUser(getUserId());
        return AjaxJson.getSuccess();
    }

    /**
     * 修改密码
     */
    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePwd")
    public AjaxJson updatePwd(@RequestBody @Valid UpdatePwdVO vo) {
        SysUser user = userService.getUserInfoById(getUserId());
        if (!user.getPassword().equals(vo.getOldPassword()))
        {
            throw new BusinessException("修改密码失败，旧密码错误");
        }
        if (user.getPassword().equals(vo.getNewPassword()))
        {
            throw new BusinessException("新密码不能与旧密码相同");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserId(user.getUserId());
        sysUser.setPassword(vo.getNewPassword());
        sysUser.setPwdUpdateDate(DateUtils.getNowDate());
        if (userService.updateById(sysUser))
        {
            userService.clearRedisUser(getUserId());
            return AjaxJson.getSuccess();
        }
        throw new BusinessException("修改密码异常，请联系管理员");
    }

    /**
     * 保存头像
     */
    @Log(title = "修改头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxJson updateAvatar(@RequestParam("avatarfile") MultipartFile file)
    {
        SysUser currentUser = userService.getUserInfoById(getUserId());
        try {
            if (!file.isEmpty()) {
                String avatar = FileUploadUtils.upload(SystemConfig.getAvatarPath(), file);
                currentUser.setAvatar(avatar);
                if (userService.updateUser(currentUser))
                {
                    userService.clearRedisUser(getUserId());
                    return AjaxJson.getSuccessData(avatar);
                }
            }
        }
        catch (Exception e) {
            log.error("修改头像失败！", e);
        }
        throw new BusinessException("修改头像失败");
    }

}
